<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>OCR 调试界面</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .main-container { max-width: 900px; margin: 20px auto; }
        .image-preview { max-width: 100%; margin-top: 10px; }
        .loading { display: none; text-align: center; margin: 20px 0; }
        .result-section { display: none; margin-top: 20px; }
        pre { background: #f8f9fa; padding: 10px; border-radius: 4px; max-height: 300px; overflow: auto; }
    </style>
</head>
<body>
<div class="container main-container">
    <h2 class="mb-4">OCR 功能调试</h2>
    <!-- Nav tabs -->
    <ul class="nav nav-pills mb-3" id="pills-tab" role="tablist">
        <li class="nav-item" role="presentation">
            <button class="nav-link active" id="text-tab" data-bs-toggle="pill" data-bs-target="#text" type="button">文本OCR</button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="table-tab" data-bs-toggle="pill" data-bs-target="#table" type="button">营养表OCR</button>
        </li>
    </ul>
    <div class="tab-content" id="pills-tabContent">
        <!-- 文本OCR Pane -->
        <div class="tab-pane fade show active" id="text" role="tabpanel">
            <form id="form-text" enctype="multipart/form-data">
                <div class="mb-3">
                    <label for="file-text" class="form-label">选择图像</label>
                    <input type="file" id="file-text" name="file" class="form-control" accept="image/*">
                </div>
                <button type="submit" class="btn btn-primary">开始文本OCR</button>
            </form>
            <div class="loading" id="loading-text">
                <div class="spinner-border text-primary"></div><span> 识别中...</span>
            </div>
            <div class="result-section" id="result-text">
                <h5>原图预览：</h5>
                <img id="preview-text" class="image-preview" src="" alt="原图">
                <h5 class="mt-3">识别结果:</h5>
                <table class="table table-bordered">
                    <thead><tr><th>#</th><th>文本</th><th>置信度</th></tr></thead>
                    <tbody id="table-text"></tbody>
                </table>
                <h5 class="mt-3">完整 JSON:</h5>
                <pre id="json-text"></pre>
            </div>
        </div>
        <!-- 表格OCR Pane -->
        <div class="tab-pane fade" id="table" role="tabpanel">
            <form id="form-table" enctype="multipart/form-data">
                <div class="mb-3">
                    <label for="file-table" class="form-label">选择图像</label>
                    <input type="file" id="file-table" name="file" class="form-control" accept="image/*">
                </div>
                <button type="submit" class="btn btn-success">开始营养表OCR</button>
            </form>
            <div class="loading" id="loading-table">
                <div class="spinner-border text-success"></div><span> 识别中...</span>
            </div>
            <div class="result-section" id="result-table">
                <h5>上传图片预览：</h5>
                <img id="preview-table" class="image-preview" src="" alt="原图">
                <h5 class="mt-3">预处理后图像:</h5>
                <img id="preview-preprocessed" class="image-preview" src="" alt="预处理图像">
                <h5 class="mt-3">提取的 Name-Value 对:</h5>
                <table class="table table-sm table-striped">
                  <thead><tr><th>#</th><th>名称</th><th>值</th></tr></thead>
                  <tbody id="debug-pairs"></tbody>
                </table>
                <h5 class="mt-3">识别出的原始表格 JSON:</h5>
                <pre id="json-debug"></pre>
                <h5 class="mt-3">匹配结果:</h5>
                <table class="table table-hover">
                    <thead><tr><th>#</th><th>名称</th><th>数值</th><th>单位</th><th>是否匹配</th><th>原始OCR</th></tr></thead>
                    <tbody id="table-nutrition"></tbody>
                </table>

            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
// 文本 OCR
const formText = document.getElementById('form-text');
formText.addEventListener('submit', e => {
    e.preventDefault();
    const fileInput = document.getElementById('file-text');
    if (!fileInput.files.length) return alert('请选择图片');
    const form = new FormData(); form.append('file', fileInput.files[0]);
    document.getElementById('loading-text').style.display = 'block';
    document.getElementById('result-text').style.display = 'none';
    fetch('http://localhost:8181/api/recognize', { method:'POST', body: form })
      .then(r=>r.json()).then(data=>{
        document.getElementById('preview-table').src = URL.createObjectURL(fileInput.files[0]);
        document.getElementById('preview-preprocessed').src = `http://localhost:8181/static/${data.debugPreprocessedPath.split('/').pop()}`;

        // 填充 name-value 原始对
        const pairs = document.getElementById('debug-pairs');
        pairs.innerHTML = '';
        (data.debugRawPairs || []).forEach((p, i) => {
          const tr = document.createElement('tr');
          tr.innerHTML = `<td>${i + 1}</td><td>${p.name}</td><td>${p.value}</td>`;
          pairs.appendChild(tr);
        });

        // 显示原始表格 JSON
        document.getElementById('json-debug').textContent = data.debugTables;
      }).catch(err=>{alert('出错:'+err);});
});

// 表格OCR处理逻辑修改
const formTable = document.getElementById('form-table');
formTable.addEventListener('submit', async e => {
    e.preventDefault();
    const fileInput = document.getElementById('file-table');
    if (!fileInput.files.length) return alert('请选择图片');

    try {
        // 显示加载状态
        document.getElementById('loading-table').style.display = 'block';
        document.getElementById('result-table').style.display = 'none';

        // 发送请求
        const form = new FormData();
        form.append('file', fileInput.files[0]);
        const response = await fetch('http://localhost:8181/api/recognize/nutrition-table', {
            method: 'POST',
            body: form
        });

        if (!response.ok) throw new Error(`HTTP错误 ${response.status}`);
        const data = await response.json();

        // 更新预览图片
        document.getElementById('preview-table').src = URL.createObjectURL(fileInput.files[0]);
        document.getElementById('preview-preprocessed').src = data.debugPreprocessedPath;

        // 显示原始键值对
        const pairsTbody = document.getElementById('debug-pairs');
        pairsTbody.innerHTML = data.debugRawPairs.map((p, i) => `
            <tr>
                <td>${i + 1}</td>
                <td>${p.name}</td>
                <td>${p.value}</td>
            </tr>
        `).join('');

        // 显示原始表格数据
        const debugTables = document.getElementById('json-debug');
        debugTables.innerHTML = data.debugTables.map(table => `
            <div class="mb-4">
                <h6>表格头：${table.headers.join(', ')}</h6>
                <table class="table table-sm table-bordered">
                    ${table.rows.map(row => `
                        <tr>
                            ${row.map(cell => `<td>${cell}</td>`).join('')}
                        </tr>
                    `).join('')}
                </table>
            </div>
        `).join('');

        // 显示匹配结果
        const nutritionTbody = document.getElementById('table-nutrition');
        nutritionTbody.innerHTML = data.results.map((item, i) => `
            <tr class="${item.isMatched ? 'table-success' : 'table-danger'}">
                <td>${i + 1}</td>
                <td>${item.nutritionName}</td>
                <td>${item.amount ?? '-'}</td>
                <td>${item.unit || '-'}</td>
                <td>${item.isMatched ? '✅' : '❌'}</td>
                <td>${item.ocrName || '-'}</td>
            </tr>
        `).join('');

        // 显示结果区域
        document.getElementById('loading-table').style.display = 'none';
        document.getElementById('result-table').style.display = 'block';

    } catch (err) {
        alert('处理失败: ' + err.message);
        document.getElementById('loading-table').style.display = 'none';
    }
});
</script>
</body>
</html>
